#!/usr/bin/env perl
use 5.018;
use warnings;
use utf8;
use lib 'lib';
use Gerrit::API;
use Gerrit::Link;
use Mojo::IOLoop;
use DTask::Link;

use Data::Dumper;

use Mango;
my $mango = Mango->new;
DTask::Link::setMango($mango);


Gerrit::API::getChanges(q => 'status:open', sub {
	my ($ret) = @_;
	unless ($ret->{error})
	{
		#warn Dumper $ret->{result};

		my @cl_nums;
		for ( @{ $ret->{result} })
		{
			# ignore project only-for-test
			push @cl_nums, $_->{_number} if $_->{project} ne 'only-for-test';
		}

		say join ", ", @cl_nums;
		if (@cl_nums)
		{
			my $delay = Mojo::IOLoop->delay(sub {
				warn 'scan gerrit CLs commit message rebuild dtask database done';
				Mojo::IOLoop->stop;
			});

			for my $cl_num (@cl_nums)
			{
				my $end = $delay->begin;
				Gerrit::API::getChangeCommitMessage($cl_num,sub {
					my ($ret) = @_;
					unless ($ret->{error})
					{
						my $commit_message = $ret->{result};
						Gerrit::Link::createLinkByCLCommitMessage($cl_num , $commit_message , $end);
					}
					else
					{
						warn "get commit message on error";
						$end->();
					}
					
				});
			}
		}
	}
});

Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
